import datetime

from lab.common.enums import MessageTypeEnum
from lab.message.models import Message, UserMessageView
from lab.user.models import ExtendedUser


class MessageService:
    @staticmethod
    def add_message(entity_id: int, message_type: MessageTypeEnum, content: str, user_id: int) -> None:
        """
            entity_id 传入对应的id
            message_type: 消息类型
            content: 消息内容 （拒绝或者同意请求的原因）

        创建消息，根据类型等基本信息创建消息Record
        """
        message = {"message_type": message_type.get_message_code(), "create_time": datetime.datetime.now(),
                   "entity_id": entity_id, "content": content}
        message_result = Message.objects.create(**message)
        if (message_type == MessageTypeEnum.NEW_DEVICE) or (
                message_type == MessageTypeEnum.PRESERVE_DEVICE):
            # insert or user and message into table
            user_list = ExtendedUser.objects.filter().all()
            all_user_message_view = []
            for user in user_list:
                user_message_view = {"message_id": message_result.id, "user_id": user.id, "is_read": 0}

                all_user_message_view.append(user_message_view)
            UserMessageView.objects.bulk_create(all_user_message_view)
        else:
            user_message_view = {"message_id": message_result.id, "user_id": user_id, "is_read": 0}
            UserMessageView.objects.create(**user_message_view)

    def update_message_read_status(self, message_id, user_id):
        message_read_status = UserMessageView.objects.filter(message_id=message_id).filter(user_id).first()
        if message_read_status is None:
            return False
        is_read_status = message_read_status.is_read
        message_read_status.update(is_read=1 - is_read_status)

    @staticmethod
    def get_message_user_view_by_message_id_and_user_id(message_id, user_id, user_message_list):
        for message in user_message_list:
            if message.user_id == user_id and message.message_id == message_id:
                return message
        return None

    @staticmethod
    def get_message_by_entity_id(entity_id, message_list, message_type):
        for message in message_list:
            if message.entity_id == entity_id and message.message_type == message_type:
                return message

        return None
